package com.shopping_back.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shopping_back.mapper.SkuMapper;
import com.shopping_back.pojo.dto.CartItemDTO;
import com.shopping_back.pojo.dto.CartResponse;
import com.shopping_back.pojo.entity.CartItem;
import com.shopping_back.mapper.CartItemMapper;
import com.shopping_back.pojo.entity.Sku;
import com.shopping_back.service.ICartItemService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 购物车商品表 服务实现类
 * </p>
 *
 * @author Jack
 * @since 2025-07-12
 */
@Service
@RequiredArgsConstructor
public class CartItemServiceImpl extends ServiceImpl<CartItemMapper, CartItem> implements ICartItemService {

    private final ObjectMapper objectMapper = new ObjectMapper();

    private final CartItemMapper cartItemMapper;

    private final SkuMapper skuMapper;

    private final HttpServletRequest request; // 自动注入


    @Override
    public CartResponse getCartItems(Long userId, int page, int size) {
        Page<CartItem> pageInfo = new Page<>(page, size);
        // 使用 MyBatis Plus 分页，但只为获取 total 和分页参数
        cartItemMapper.selectPage(pageInfo, new LambdaQueryWrapper<CartItem>()
                .eq(CartItem::getUserId, userId));

        // 自定义关联查询
        List<CartItemDTO> cartItems = cartItemMapper.selectCartItemsWithProduct(userId);

        // 处理 specsJson 并拼接 productName
        for (CartItemDTO item : cartItems) {
            try {
                if (item.getSpecsJson() != null) {
                    // 使用 Map<String, Object> 处理混合类型
                    Map<String, Object> specs = objectMapper.readValue(item.getSpecsJson(), Map.class);
                    String specsStr = specs.entrySet().stream()
                            .map(entry -> entry.getKey() + ":" + entry.getValue().toString()) // 转换为字符串
                            .collect(Collectors.joining(","));
                    item.setProductName(item.getProductName() + " - " + specsStr);
                } else {
                    item.setProductName(item.getProductName());
                }
            } catch (Exception e) {
                item.setProductName(item.getProductName());
                System.err.println("Failed to parse specsJson: " + e.getMessage());
            }
            item.setSpecsJson(null); // 清空临时字段
        }
        // 手动实现分页
        int start = (page - 1) * size;
        int end = Math.min(start + size, cartItems.size());
        List<CartItemDTO> pagedItems = start < cartItems.size() ? cartItems.subList(start, end) : new ArrayList<>();

        CartResponse response = new CartResponse();
        response.setData(pagedItems);
        response.setTotal(cartItems.size());
        return response;
    }

    @Override
    public void removeCartItem(Long id) {
        cartItemMapper.deleteById(id);
    }
    public void addToCart(CartItemDTO dto) {
        // 1. 校验SKU
        Sku sku = skuMapper.selectById(dto.getProductId());
        if (sku == null) throw new IllegalArgumentException("商品不存在");
        if (sku.getStock() < dto.getQuantity()) throw new IllegalArgumentException("库存不足");

        // 2. 检查是否已存在记录
        CartItem existing = cartItemMapper.selectByUserAndProduct(dto.getUserId(), dto.getProductId());
        if (existing != null) {
            existing.setQuantity(existing.getQuantity() + dto.getQuantity());
            cartItemMapper.updateById(existing);
        } else {
            CartItem newItem = new CartItem();
            newItem.setUserId(dto.getUserId());
            newItem.setSkuId(dto.getProductId());
            newItem.setQuantity(dto.getQuantity());
            newItem.setSelected(true);
            newItem.setCreateTime(LocalDateTime.now());
            cartItemMapper.insert(newItem);
        }
    }

}
